import 'package:demo_app_video/commons/cache_manger.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:demo_app_video/commons/http/http.dart';
import 'package:flutter_adcontent/flutter_adcontent.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:keframe/keframe.dart';
import 'package:demo_app_video/commons/router/routes.dart';

class VideosListsData extends StatefulWidget {
  String cid = '0';
  VideosListsData({Key? key, required this.cid}) : super(key: key);

  @override
  State<VideosListsData> createState() => _VideosListsDataState();
}

class _VideosListsDataState extends State<VideosListsData> {
  List videos = [];
  int pageNum = 1; // 当前页数
  int totalPages = 1;
  bool isLoading = false; // 是否正在加载
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    get_videos();
  }

  get_videos({isRefresh = false}) async {
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
    });
    String url = 'shortplay/list';
    if (widget.cid == '11111111111') {
      url = 'shortplay/hot_list';
    }
    var resultData = await HttpUtil.getInstance()
        .get('${url}', data: {'page': pageNum, 'cid': widget.cid});
    if (resultData['code'] == 1) {
      if (isRefresh) {
        videos = resultData['data']['data'];
      } else {
        videos.addAll(resultData['data']['data']);
      }
      totalPages = resultData['data']['last_page'];
    }
    setState(() {
      isLoading = false;
    });
  }

  Future<void> onLoad() async {
    if (pageNum >= totalPages) return;
    setState(() {
      pageNum++;
    });
    await get_videos(isRefresh: false);
  }

  Future<void> onRefresh() async {
    videos.clear();
    setState(() {
      pageNum = 1;
    });
    await get_videos(isRefresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return SizeCacheWidget(
        child: EasyRefresh(
      header: ClassicHeader(
          processedText: "刷新完成",
          processingText: "正在刷新",
          readyText: '准备刷新',
          armedText: "松手刷新",
          dragText: "下拉刷新",
          showMessage: false),
      footer: ClassicFooter(
          processedText: "加载完成",
          processingText: "正在加载",
          readyText: '准备加载',
          armedText: "松手加载",
          dragText: "上拉加载",
          showMessage: false),
      child: GridView.builder(
          padding: EdgeInsets.only(left: 16.w, right: 16.w),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 104.w / 210.h,
            crossAxisSpacing: 8.w,
          ),
          itemCount: videos.length,
          addAutomaticKeepAlives: false,
          addRepaintBoundaries: false,
          itemBuilder: (context, index) {
            var item = videos[index];

            return GestureDetector(
              child: Container(
                width: 104.w,
                child: Column(
                  children: [
                    FrameSeparateWidget(
                        child: ClipRRect(
                      borderRadius: BorderRadius.circular(4.w),
                      child: CachedNetworkImage(
                        // cacheManager: CustomCacheManager.instance,
                        imageUrl: '${item['thumb_image']}',
                        placeholder: (BuildContext context, value) {
                          return Center(
                            child: Text(
                              '加载中~',
                              style: TextStyle(
                                  color: Color(0xff999999), fontSize: 12.sp),
                            ),
                          );
                        },
                        width: 104.w,
                        height: 146.h,
                        fit: BoxFit.fill,
                        useOldImageOnUrlChange: true,
                        memCacheHeight: 400,
                        memCacheWidth: 400,
                        maxHeightDiskCache: 400,
                        maxWidthDiskCache: 400,
                      ),
                    )),
                    Container(
                      height: 8.h,
                    ),
                    Container(
                      alignment: Alignment.topLeft,
                      child: Text(
                        '${item['display_name']}',
                        style: TextStyle(
                            fontSize: 13.sp, fontWeight: FontWeight.bold),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    Container(
                      height: 6.h,
                    ),
                    Container(
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            decoration: BoxDecoration(
                                color: Color(0xffEBE1E1),
                                borderRadius: BorderRadius.circular(3.sp)),
                            padding: EdgeInsets.only(
                                top: 3.h, bottom: 3.h, left: 4.w, right: 4.w),
                            child: Text(
                              '${item['category_tags']}',
                              style: TextStyle(
                                  color: Color(0xff666666), fontSize: 10.sp),
                            ),
                          ),
                          Expanded(child: Container()),
                          Image.asset(
                            'images/lists_bofang.png',
                            width: 6.w,
                            height: 8.h,
                          ),
                          Container(
                            width: 4.w,
                          ),
                          Text(
                            '${item['follow_num']}',
                            style: TextStyle(
                                color: Color(0xff999999), fontSize: 10.sp),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              ),
              onTap: () async {
                var resultData = await FlutterAdcontent.requestDrama(
                    [int.parse(item['third_movie_id'].toString())]);
                Routes().push(
                    context, Routes.dramaDetails, {'drama': resultData.first});
              },
            );
          }),
      onLoad: onLoad,
      onRefresh: onRefresh,
    ));
  }
}

class ItemData extends StatelessWidget {
  var item;
  ItemData({Key? key, this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 104.w,
      child: Column(
        children: [
          // ClipRRect(
          //   borderRadius: BorderRadius.circular(4.w),
          //   child: CachedNetworkImage(
          //     imageUrl: '${item['thumb_image']}',
          //     width: 104.w,
          //     height: 146.h,
          //     fit: BoxFit.fill,
          //     useOldImageOnUrlChange: true,
          //   ),
          // ),
          ClipRRect(
            borderRadius: BorderRadius.circular(4.w),
            child: Image.network(
              '${item['thumb_image']}',
              width: 104.w,
              height: 146.h,
              fit: BoxFit.fill,
            ),
          ),
          Container(
            height: 8.h,
          ),
          Container(
            alignment: Alignment.topLeft,
            child: Text(
              '${item['display_name']}',
              style: TextStyle(fontSize: 13.sp, fontWeight: FontWeight.bold),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Container(
            height: 6.h,
          ),
          Container(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  decoration: BoxDecoration(
                      color: Color(0xffEBE1E1),
                      borderRadius: BorderRadius.circular(3.sp)),
                  padding: EdgeInsets.only(
                      top: 3.h, bottom: 3.h, left: 4.w, right: 4.w),
                  child: Text(
                    '${item['category_tags']}',
                    style: TextStyle(color: Color(0xff666666), fontSize: 10.sp),
                  ),
                ),
                Expanded(child: Container()),
                Image.asset(
                  'images/lists_bofang.png',
                  width: 6.w,
                  height: 8.h,
                ),
                Container(
                  width: 4.w,
                ),
                Text(
                  '93.66万',
                  style: TextStyle(color: Color(0xff999999), fontSize: 10.sp),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
